<template>
  <div class="post-processing-node">
    <div class="node-header">
      <h3 class="node-title">后期处置</h3>
      <el-button type="primary" @click="handleComplete" :disabled="isCompleted">
        完成后期处置
      </el-button>
    </div>

    <div class="processing-layout">
      <!-- 左侧处理进展 -->
      <div class="processing-progress">
        <div class="section-title">处理进展</div>
        
        <div class="progress-records">
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in nodeList"
              :key="record.id || index"
              :timestamp="formatDateTime(record.createTime)"
              :type="record.status === 1 ? 'success' : 'primary'"
            >
              {{ record.nodeName }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <!-- 右侧处理节点列表 -->
      <div class="processing-nodes">
        <div class="section-title">处理节点</div>
        
        <div class="table-operations">
          <el-button type="primary" @click="handleAdd" :disabled="isCompleted">
            <el-icon><Plus /></el-icon>新增节点
          </el-button>
        </div>
        
        <el-table v-loading="loading" :data="nodeList" stripe border>
          <el-table-column label="节点名称" prop="nodeName" min-width="150" show-overflow-tooltip />
          <el-table-column label="预计耗时(小时)" prop="expectedHours" width="120" />
          <el-table-column label="节点状态" prop="status" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'warning' : 'success'">
                {{ row.status === 1 ? '进行中' : '已完成' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="节点进行时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.processTime || row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="节点类型" prop="nodeType" width="120">
            <template #default="{ row }">
              <el-tag :type="getNodeTypeTag(row.nodeType)">
                {{ getNodeTypeName(row.nodeType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="note" min-width="180" show-overflow-tooltip />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)" :disabled="isCompleted">编辑</el-button>
              <el-button v-if="row.status === 1" link type="success" @click="handleCompleteNode(row)" :disabled="isCompleted">完成</el-button>
              <el-button link type="danger" @click="handleDelete(row)" :disabled="isCompleted">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          v-if="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 提示信息 -->
    <div class="tip-section">
      <el-alert
        title="添加并完成所有处理节点后，点击'完成后期处置'进入应急总结阶段"
        type="success"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" append-to-body>
      <el-form ref="nodeFormRef" :model="nodeForm" :rules="nodeRules" label-width="100px">
        <el-form-item label="节点名称" prop="nodeName">
          <el-input v-model="nodeForm.nodeName" placeholder="请输入节点名称" />
        </el-form-item>
        <el-form-item label="预计耗时" prop="expectedHours">
          <el-input-number v-model="nodeForm.expectedHours" :min="0.5" :step="0.5" placeholder="请输入预计耗时(小时)" style="width: 100%" />
        </el-form-item>
        <el-form-item label="节点状态" prop="status">
          <el-select v-model="nodeForm.status" placeholder="请选择节点状态" style="width: 100%">
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="节点进行时间" prop="processTime">
          <el-date-picker
            v-model="nodeForm.processTime"
            type="datetime"
            placeholder="选择节点进行时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="节点类型" prop="nodeType">
          <el-select v-model="nodeForm.nodeType" placeholder="请选择节点类型" style="width: 100%">
            <el-option label="审批节点" :value="1" />
            <el-option label="处理节点" :value="2" />
            <el-option label="结束节点" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="nodeForm.note" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 完成处置确认框 -->
    <el-dialog v-model="completeDialogVisible" title="完成后期处置" width="400px">
      <div class="confirm-content">
        <el-icon :size="48" color="#67C23A"><CircleCheck /></el-icon>
        <p class="confirm-message">确定要完成后期处置阶段吗？</p>
        <p class="confirm-desc">完成后将进入应急总结阶段，无法返回修改</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="completeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmComplete">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, defineProps, defineEmits } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getFlowList, getFlowDetail, addFlow, updateFlow, deleteFlow } from '@/api/bridge/command/flow';
import { updateEmergencyEvent } from '@/api/bridge/command/event';
import dayjs from 'dayjs';
import { Plus, CircleCheck } from '@element-plus/icons-vue';

const props = defineProps({
  eventData: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['next-step']);

// 数据列表
const loading = ref(false);
const nodeList = ref([]);
const total = ref(0);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: 2, // 后期处置类型
  eventId: '',
});

// 对话框显示控制
const dialogVisible = ref(false);
const dialogTitle = computed(() => {
  return nodeForm.value.id ? '编辑节点' : '新增节点';
});
const nodeFormRef = ref();
const nodeForm = ref<Record<string, any>>({
  id: undefined,
  nodeName: '',
  expectedHours: 1,
  status: 1, // 默认进行中
  nodeType: 2, // 默认处理节点
  note: '',
  type: 2, // 后期处置类型
  eventId: '',
  processTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), // 默认当前时间
});

// 表单验证规则
const nodeRules = {
  nodeName: [{ required: true, message: '请输入节点名称', trigger: 'blur' }],
  expectedHours: [{ required: true, message: '请输入预计耗时', trigger: 'blur' }],
  nodeType: [{ required: true, message: '请选择节点类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择节点状态', trigger: 'change' }],
  processTime: [{ required: true, message: '请选择节点进行时间', trigger: 'change' }],
};

// 节点类型字典
const getNodeTypeName = (nodeType: number) => {
  const types: Record<number, string> = {
    1: '审批节点',
    2: '处理节点',
    3: '结束节点'
  };
  return types[nodeType] || '未知';
};

// 节点类型标签
const getNodeTypeTag = (nodeType: number) => {
  const tags: Record<number, 'primary' | 'success' | 'danger' | 'info' | 'warning'> = {
    1: 'primary',
    2: 'success',
    3: 'danger'
  };
  return tags[nodeType] || 'info';
};

// 获取节点列表
const getNodeList = async () => {
  loading.value = true;
  try {
    // 确保设置了eventId
    if (!queryParams.eventId && props.eventData && props.eventData.id) {
      queryParams.eventId = props.eventData.id;
    }
    
    const res = await getFlowList(queryParams);
    if (res.code === 200) {
      nodeList.value = res.rows || [];
      total.value = res.total || 0;
    }
  } catch (error) {
    console.error('获取节点列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getNodeList();
};

const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getNodeList();
};

// 新增节点
const handleAdd = () => {
  resetForm();
  nodeForm.value.eventId = props.eventData.id;
  nodeForm.value.type = 2; // 后期处置类型
  nodeForm.value.processTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 默认当前时间
  dialogVisible.value = true;
};

// 编辑节点
const handleEdit = async (row: any) => {
  resetForm();
  const id = row.id || row.processFlowLogId;
  try {
    const res = await getFlowDetail(id);
    if (res.code === 200) {
      nodeForm.value = {
        ...res.data,
        processTime: res.data.processTime || res.data.createTime || dayjs().format('YYYY-MM-DD HH:mm:ss')
      };
    }
  } catch (error) {
    console.error('获取节点详情失败:', error);
  }
  dialogVisible.value = true;
};

// 完成节点
const handleCompleteNode = async (row: any) => {
  try {
    const data = { 
      ...row, 
      status: 2, // 设置为已完成
      note: row.note || `节点"${row.nodeName}"已完成`
    };
    const res = await updateFlow(data);
    if (res.code === 200) {
      ElMessage.success('节点已完成');
      getNodeList();
    } else {
      ElMessage.error(res.msg || '操作失败');
    }
  } catch (error) {
    console.error('完成节点失败:', error);
    ElMessage.error('操作失败');
  }
};

// 删除节点
const handleDelete = (row: any) => {
  const id = row.id || row.processFlowLogId;
  ElMessageBox.confirm('确定要删除该节点吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteFlow(id);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        getNodeList();
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除节点失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  nodeForm.value = {
    id: undefined,
    nodeName: '',
    expectedHours: 1,
    status: 1,
    nodeType: 2,
    note: '',
    type: 2, // 后期处置类型
    eventId: props.eventData ? props.eventData.id : '',
    processTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), // 默认当前时间
  };
  
  if (nodeFormRef.value) {
    nodeFormRef.value.resetFields();
  }
};

// 提交表单
const submitForm = async () => {
  if (!nodeFormRef.value) return;
  await nodeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const hasId = !!nodeForm.value.id;
        const actionApi = hasId ? updateFlow : addFlow;
        const res = await actionApi(nodeForm.value);
        
        if (res.code === 200) {
          ElMessage.success(hasId ? '修改成功' : '新增成功');
          dialogVisible.value = false;
          getNodeList();
        } else {
          ElMessage.error(res.msg || (hasId ? '修改失败' : '新增失败'));
        }
      } catch (error) {
        const hasId = !!nodeForm.value.id;
        console.error(hasId ? '修改节点失败:' : '新增节点失败:', error);
        ElMessage.error(hasId ? '修改失败' : '新增失败');
      }
    }
  });
};

// 完成处置相关
const completeDialogVisible = ref(false);

// 处理完成处置按钮点击
const handleComplete = () => {
  // 检查是否有未完成的节点
  const hasUnfinishedNode = nodeList.value.some(node => node.status === 1);
  if (hasUnfinishedNode) {
    ElMessageBox.confirm('还有未完成的节点，确定要完成后期处置吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      completeDialogVisible.value = true;
    }).catch(() => {});
  } else {
    completeDialogVisible.value = true;
  }
};

// 确认完成处置
const confirmComplete = async () => {
  try {
    ElMessage.success('后期处置已完成，进入应急总结阶段');
    completeDialogVisible.value = false;
    emit('next-step');
  } catch (error) {
    console.error('完成后期处置失败:', error);
    ElMessage.error('操作失败');
  }
};

// 格式化日期时间
const formatDateTime = (date: string) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

const isCompleted = computed(() => {
  return props.eventData && props.eventData.flowStatus === 7;
});

onMounted(() => {
  // 设置事件ID
  if (props.eventData && props.eventData.id) {
    queryParams.eventId = props.eventData.id;
    nodeForm.value.eventId = props.eventData.id;
  }
  
  // 获取节点列表
  getNodeList();
});
</script>

<style scoped lang="scss">
.post-processing-node {
  padding: 20px;
  
  .node-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .node-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: var(--el-text-color-primary);
    }
  }
  
  .processing-layout {
    display: grid;
    grid-template-columns: 300px 1fr;
    gap: 20px;
    margin-bottom: 24px;
    
    @media (max-width: 992px) {
      grid-template-columns: 1fr;
    }
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    color: var(--el-text-color-primary);
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 16px;
      background-color: var(--el-color-primary);
      margin-right: 8px;
      border-radius: 2px;
    }
  }
  
  .processing-progress {
    background-color: var(--el-bg-color-overlay);
    border-radius: 4px;
    padding: 16px;
    box-shadow: var(--el-box-shadow-light);
    
    .progress-records {
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;
    }
  }
  
  .processing-nodes {
    background-color: var(--el-bg-color-overlay);
    border-radius: 4px;
    padding: 16px;
    box-shadow: var(--el-box-shadow-light);
    
    .table-operations {
      margin-bottom: 16px;
      display: flex;
      justify-content: flex-end;
    }
    
    .el-pagination {
      margin-top: 16px;
      justify-content: flex-end;
    }
  }
  
  .tip-section {
    margin-top: 20px;
  }
  
  .confirm-content {
    text-align: center;
    padding: 20px 0;
    
    .confirm-message {
      font-size: 16px;
      font-weight: 500;
      margin: 16px 0 8px;
      color: var(--el-text-color-primary);
    }
    
    .confirm-desc {
      color: var(--el-text-color-secondary);
      margin: 0;
    }
  }
}
</style> 